var _ = require('lodash'),
    Q = require('q'),
    mongoose = require('mongoose'),
    BaseEnum = require('../../../Base/server/controllers/Enum'),
    BaseFun = require('../../../Base/server/controllers/Function'),
    Transaction = require('../../../Base/server/controllers/Transaction'),
    entityCollection = require('../../../Base/server/controllers/EntityCollection'),
    barcodeMasterController = require('../../../Barcode/server/controllers/BarcodeMaster.server.controller'),
    operationController = require('../../../CBO/server/controllers/Operation.server.controller'),
    kanbanDemandController = require('../../../ProduceWork/server/controllers/KanbanDemand.server.controller'),
    rcvRecordController = require('../../../ProduceWork/server/controllers/RcvRecord.server.controller'),
    connectAreaController = require('../../../CBO/server/controllers/WareHouse.server.controller'),
    departmentController = require('../../../CBO/server/controllers/Department.server.controller'),
    terminalController = require('../../../CBO/server/controllers/Terminal.server.controller'),
    DeliveryRecordController = require('../../../ProduceWork/server/controllers/DeliveryRecord.server.controller'),
    bizRecordController = require('../../../Barcode/server/controllers/BizRecord.server.controller'),
    MOController = require('../../../ProduceReady/server/controllers/MO.server.contorller'),
    wareHouseController = require('../../../CBO/server/controllers/WareHouse.server.controller'),
    SocketIo = require('../../../Base/server/controllers/Socket'),
    ExtendEnumFunction = require('../../../Common/server/controllers/ExtendEnum.server.function'),
    ContainerController = require('../../../CBO/server/controllers/Container.server.controller');


exports.createKanban = function(req, res) {
    var parameter = req.body.Parameter,
        barcode = parameter.Barcode,
        userId = req.user._id;

    checkKanbanExist(barcode).then(function(result) {
            return Q.when(result.exist ? result.MO : createKanbanRecords(result.MO, userId));
        }).then(function(results) {
            res.json({
                Data: true,
                Error: null
            });
        }).catch(function(err) {
            res.json({
                Data: null,
                Error: err
            });
        })
        .done();
};

function checkKanbanExist(barcode) {
    var deferred = Q.defer();

    barcodeMasterController.findBarcodeMaster(barcode, function(err, barcodeMaster) {
        if (err) {
            deferred.reject(err);
            return;
        }
        if (!barcodeMaster || barcodeMaster.BarcodeType != 0) {
            var newErr = new Error();
            newErr.leval = 9;
            newErr.title = '查询物料错误';
            newErr.message = '无法识别的芯片，请重新扫描！';
            deferred.reject(newErr);
            return;
        }
        kanbanDemandController.findOneByMoId(barcodeMaster.MO, function(err, demands) {
            if (err) {
                deferred.reject(err);
                return;
            }
            deferred.resolve({
                exist: demands ? true : false,
                MO: barcodeMaster.MO
            });
        });
    });

    return deferred.promise;
}

function createKanbanRecords(Mo, userId) {
    var deferred = Q.defer();

    connectAreaController.distinctId(function(err, areaIds) {
        if (err) {
            deferred.reject(err);
            return;
        }
        var kanbanDemandRecords = [];
        _.forEach(areaIds, function(areaId) {
            kanbanDemandRecords.push({
                RowStatus: BaseEnum.RowStatus.Insert.Value,
                CreatedBy: userId,
                MO: Mo,
                ConnectArea: areaId
            });
        });
        Transaction.BatchSaveByTran([{
                EntityName: 'KanbanDemand',
                Records: kanbanDemandRecords
            }],
            function(err, result) {
                if (err) {
                    deferred.reject(err);
                    return;
                }
                deferred.resolve(result);
            }
        );
    });

    return deferred.promise;
}
//通过终端获取交接区
exports.queryConnectAreaByTerminal = function(req, res) {
    var parameter = req.body.Parameter,
        uniqueID = parameter.uniqueID,
        isUp = true;
    if (parameter.isUp) {
        isUp = parameter.isUp;
    }
    terminalController.findByUniqueID(uniqueID, function(err, record) {
        if (err) {
            res.json({
                Data: null,
                Error: err
            });
            return;
        }
        if (record._id) {
            var entity = entityCollection.getEntity("StationTerminal");
            entity.findOne({
                    Terminal: record._id
                }, [{
                    path: 'WorkLocation',
                    select: 'Department'
                }],
                function(err, result) {
                    if (err) {
                        res.json({
                            Data: null,
                            Error: err
                        });
                    } else {
                        var queryCondition;
                        if (isUp) {
                            queryCondition = {
                                UpDepartment: result.WorkLocation.Department
                            };
                        } else {
                            queryCondition = {
                                DownDepartment: record.WorkLocation.Department
                            };
                        }
                        //通过用户部门获取交界区
                        connectAreaController.getConnectAreaByDepartment(queryCondition, function(err, connectAreaResult) {
                            if (err) {
                                res.json({
                                    Data: null,
                                    Error: err
                                });
                            } else {
                                res.json({
                                    Data: connectAreaResult,
                                    Error: null
                                });
                            }
                        });
                    }
                });
        } else {
            res.json({
                Data: null,
                Error: "通过终端UUID未查询到相关设备。"
            });
        }
    });
};
//通过作业获取待转区
exports.queryTransferAreaByWork = function(req, res) {
    var parameter = req.body.Parameter,
        workId = parameter.workId,
        isUp = parameter.isUp;

    var queryCondition;
    if (isUp) {
        queryCondition = {
            InputWork: workId
        };
    } else {
        queryCondition = {
            TargetWork: workId
        };
    }
    connectAreaController.getWareHouseInfo(queryCondition, function(err, wareHouseInfo) {
        if (err) {
            res.json({
                Data: null,
                Error: err
            });
        } else {
            if (wareHouseInfo == null) {
                var newErr = new Error();
                newErr.leval = 9;
                newErr.title = '查询待转区失败';
                newErr.message = '未找到对应的待转区！';
                res.json({
                    Data: null,
                    Error: newErr
                });
            } else {
                res.json({
                    Data: wareHouseInfo,
                    Error: null
                });
            }

        }
    });
};

//看板id不为空（更新数据，提交本次要货量添加到累计要货量中）
//看板id为空  （添加数据）
exports.submitDemandQty = function (req, res) {
    var parameter = req.body.Parameter,
        userId = parameter.userId,
        submitData = parameter.submitData,
        wareHouseId = parameter.wareHouseId;
    var updateDatas = [];//更新数据
    var addDatas = [];//增加数据
    for (var i = 0; i < submitData.length; i++) {
        var data = submitData[i];
        if (data.KanbanId) {
            updateDatas.push({
                SysVersion: 0,
                _id: data.KanbanId,
                TotalDemandQty: data.TotalDemandQty + data.DemandQty
            });
        } else {
            addDatas.push({
                ItemMaster: data.ItemMaster,
                DescSeg1: data.DescSeg1,
                DescSeg2: data.DescSeg2,
                WareHouse: data.WareHouse,
                TotalDemandQty: data.DemandQty,
                TotalStockQty: 0,
                TotalReceiveQty: 0,
                DemandDepartment: data.DemandDepartment
            });
        }
    }
    findKanbanSysVersion(updateDatas).then(function(datas) {
        updateDatas = datas;
        var transactions = [];//保存事务的
        if(updateDatas.length>0){
            updateDatas.forEach(function(updateData) {
                updateData.RowStatus = BaseEnum.RowStatus.Modify.Value;
                updateData.CreatedBy = userId;
            });
            transactions.push({
                EntityName: 'KanbanDemand',
                Records: updateDatas
            });
        }
        if(addDatas.length>0){
            addDatas.forEach(function(addData) {
                addData._id = BaseFun.getObjectId();
                addData.RowStatus = BaseEnum.RowStatus.Insert.Value;
                addData.CreatedBy = userId;
            });
            transactions.push({
                EntityName: 'KanbanDemand',
                Records: addDatas
            });
        }

        return Q.nfcall(Transaction.BatchSaveByTran, transactions);
    }).then(function() {
        SocketIo.emit(wareHouseId.toString(), 1);
        res.json({
            Data: true,
            Error: null
        });
    }).catch(function(err) {
        res.json({
            Data: null,
            Error: err
        });
    })
    .done();
    
};
//通过看板id循环寻找SysVersion
function findKanbanSysVersion(updateDatas){
    var deferred = Q.defer();
    var promises = [];
    updateDatas.forEach(function (updateData) {
        promises.push(findOneKanbanSysVersion(updateData));   
    });
    
    Q.all(promises).then(function () {
        deferred.resolve(updateDatas);
    }, function(err) {
        deferred.reject(err);
    });
    return deferred.promise;
}

function findOneKanbanSysVersion (updateData) {
    var deferred = Q.defer();
    kanbanDemandController.findOneByKanbanId(updateData._id, function (err, result) {
        if (err) {
            deferred.reject(err);
            return;
        }
        if (result) {
            updateData.SysVersion = result.SysVersion;
        } 
        deferred.resolve(updateData);
                    
    });  
    return deferred.promise;
}


//获取看板的数据
exports.queryKanbanData = function(req, res) {
    var parameter = req.body.Parameter,
        flag = parameter.flag,
        departmentId = parameter.departmentId,
        wareHouseId = parameter.wareHouseId;

    //在入库记录表中找到对应待转区的入库数据
    rcvRecordController.queryByWareHouse(wareHouseId, function(err, rcvRecords) {

        if (err) {
            res.json({
                Data: null,
                Error: err
            });
        } else {
            if (rcvRecords == null || rcvRecords.length === 0) {
                var newErr = new Error();
                newErr.leval = 9;
                newErr.title = '查询入库记录失败';
                newErr.message = '未找到对应的入库记录！';
                res.json({
                    Data: null,
                    Error: newErr
                });
            } else {
                if (rcvRecords[0].BarcodeMaster != null) {

                    //找到不同的物料
                    var ItemMasters = [{
                        ItemMaster: rcvRecords[0].BarcodeMaster.ItemMaster,
                        ItemMasterCode: rcvRecords[0].BarcodeMaster.ItemMasterCode
                    }];
                    for (var i = 0; i < rcvRecords.length; i++) {
                        if (rcvRecords[i].BarcodeMaster === null) {
                            continue;
                        }
                        var repeat = false;
                        for (var j = 0; j < ItemMasters.length; j++) {
                            if (rcvRecords[i].BarcodeMaster.ItemMasterCode === ItemMasters[j].ItemMasterCode) {
                                repeat = true;
                                break;
                            }
                        }
                        if (!repeat) {
                            ItemMasters.push({
                                ItemMaster: rcvRecords[i].BarcodeMaster.ItemMaster,
                                ItemMasterCode: rcvRecords[i].BarcodeMaster.ItemMasterCode
                            });
                        }
                    }
                    //找到不同的尺寸
                    var DescSeg1s = [rcvRecords[0].BarcodeMaster.DescSeg1];
                    for (var i = 0; i < rcvRecords.length; i++) {
                        if (rcvRecords[i].BarcodeMaster === null) {
                            continue;
                        }
                        var repeat = false;
                        for (var j = 0; j < DescSeg1s.length; j++) {
                            if (rcvRecords[i].BarcodeMaster.DescSeg1 === DescSeg1s[j]) {
                                repeat = true;
                                break;
                            }
                        }

                        if (!repeat) {
                            DescSeg1s.push(rcvRecords[i].BarcodeMaster.DescSeg1);
                        }
                    }
                    //找到不同的外观
                    var DescSeg2s = [rcvRecords[0].BarcodeMaster.DescSeg2];
                    for (var i = 0; i < rcvRecords.length; i++) {
                        if (rcvRecords[i].BarcodeMaster === null) {
                            continue;
                        }
                        var repeat = false;
                        for (var j = 0; j < DescSeg2s.length; j++) {
                            if (rcvRecords[i].BarcodeMaster.DescSeg2 === DescSeg2s[j]) {
                                repeat = true;
                                break;
                            }
                        }

                        if (!repeat) {
                            DescSeg2s.push(rcvRecords[i].BarcodeMaster.DescSeg2);
                        }
                    }

                    //入库记录表中同一仓库数据进行分组（物料+尺寸+外观）
                    var items = [];
                    for (var i = 0; i < ItemMasters.length; i++) {
                        for (var j = 0; j < DescSeg1s.length; j++) {
                            for (var k = 0; k < DescSeg2s.length; k++) {
                                var num = 0;
                                for (var a = 0; a < rcvRecords.length; a++) {
                                    var temp = rcvRecords[a].BarcodeMaster;
                                    if (temp === null) {
                                        continue;
                                    }
                                    if (ItemMasters[i].ItemMasterCode === temp.ItemMasterCode && DescSeg1s[j] === temp.DescSeg1 && DescSeg2s[k] === temp.DescSeg2) {
                                        num++;
                                    }
                                };
                                if (num != 0) {
                                    items.push({
                                        ItemMasterCode: ItemMasters[i].ItemMasterCode,
                                        ItemMaster: ItemMasters[i].ItemMaster,
                                        DescSeg1: DescSeg1s[j],
                                        DescSeg2: DescSeg2s[k],
                                        Num: num
                                    });
                                }
                            };
                        };
                    };

                    // console.log(ItemMasters);
                    // console.log(DescSeg1s);
                    // console.log(DescSeg2s);
                    // console.log(items);

                    //存入每个分类（物料+尺寸+外观）的信息
                    var promises = [];
                    var itemDatas = [];
                    items.forEach(function(item) {
                        if (flag === "down") {

                            promises.push(queryKanbanDemand(item, wareHouseId, departmentId, itemDatas));
                        } else if (flag === "up") {

                            promises.push(queryGiveKanbanDemand(item, wareHouseId).then(function(result) {

                                itemDatas = itemDatas.concat(result);

                            }, function(error) {

                            }));
                        } else {

                        }

                    });

                    Q.all(promises).then(function() {

                        if (flag === "down") {
                            //找到看板有数据，但是库存中已经没有数据的
                            kanbanDemandController.findAllKanbanDemand(wareHouseId, departmentId, function(err, result) {

                                var resultDatas = [];
                                if (err) {
                                    res.json({
                                        Data: null,
                                        Error: err
                                    });
                                } else {
                                    if (result) {
                                        var a = 0;
                                        for (var i = 0; i < result.length; i++) {
                                            var item = result[i];
                                            a = 0;
                                            for (var j = 0; j < itemDatas.length; j++) {
                                                if (itemDatas[j].KanbanId) {
                                                    if (result[i]._id.toString() != itemDatas[j].KanbanId.toString()) {
                                                        a++;
                                                    }
                                                } else {
                                                    a++;
                                                }
                                            }
                                            if (a === itemDatas.length) {
                                                resultDatas.push({
                                                    KanbanId: item._id,
                                                    ItemMasterCode: item.ItemMaster.Code,
                                                    ItemMasterName: item.ItemMaster.Name,
                                                    DescSeg1: item.DescSeg1,
                                                    DescSeg2: item.DescSeg2,
                                                    RcvQty: 0,
                                                    TotalReceiveQty: item.TotalReceiveQty,
                                                    NeedDeliveryQty: item.TotalDemandQty - item.TotalReceiveQty,
                                                    DemandQty: 0,
                                                    TotalDemandQty: item.TotalDemandQty,
                                                    DemandDepartment: item.DemandDepartment

                                                });
                                            }

                                        }

                                        itemDatas = itemDatas.concat(resultDatas);
                                        res.json({
                                            Data: itemDatas,
                                            Error: null
                                        });
                                    } else {
                                        var newErr = new Error();
                                        newErr.leval = 9;
                                        newErr.title = '查询看板记录失败';
                                        newErr.message = '未找到对应的看板记录！';
                                        res.json({
                                            Data: null,
                                            Error: newErr
                                        });
                                    }
                                }
                            });
                        } else if (flag === "up") {
                            res.json({
                                Data: itemDatas,
                                Error: null
                            });
                        } else {

                        }

                    });

                } else {
                    res.json({
                        Data: null,
                        Error: "条码主档为空"
                    });
                }
            }
        }
    });
};
//通过（物料+尺寸+外观）和仓库id和部门id查询要货看板需求表中数据
//找到库存有数据，看板也有对应数据的和库存有数据，但看板没有对应数据的
function queryKanbanDemand(item, wareHouseId, departmentId, itemDatas) {
    var deferred = Q.defer();
    var data = {};
    kanbanDemandController.findOneKanbanDemand(item, wareHouseId, departmentId, function(err, result) {

        if (err) {
            deferred.reject(err);
        } else {
            //库存有数据，看板也有对应数据
            if (result) {
                data = {
                    KanbanId: result._id,
                    ItemMasterCode: result.ItemMaster.Code,
                    ItemMasterName: result.ItemMaster.Name,
                    DescSeg1: item.DescSeg1,
                    DescSeg2: item.DescSeg2,
                    RcvQty: item.Num,
                    TotalReceiveQty: result.TotalReceiveQty,
                    NeedDeliveryQty: result.TotalDemandQty - result.TotalReceiveQty,
                    DemandQty: 0,
                    TotalDemandQty: result.TotalDemandQty,
                    DemandDepartment: result.DemandDepartment,
                    SysVersion: result.SysVersion
                };
                itemDatas.push(data);
                deferred.resolve(itemDatas);
            }
            //库存有数据，但看板没有对应数据的，等待创建
            else {
                data = {
                    KanbanId: null,
                    ItemMasterCode: item.ItemMasterCode,
                    ItemMaster: item.ItemMaster,
                    DescSeg1: item.DescSeg1,
                    DescSeg2: item.DescSeg2,
                    RcvQty: item.Num,
                    TotalReceiveQty: 0,
                    NeedDeliveryQty: 0,
                    DemandQty: 0,
                    TotalDemandQty: 0

                };
                itemDatas.push(data);
                deferred.resolve(itemDatas);
            }
        }
    });
    return deferred.promise;
}
//通过（物料+尺寸+外观）和仓库id查询 备货看板需求表中数据
function queryGiveKanbanDemand(item, wareHouseId) {
    var deferred = Q.defer();

    kanbanDemandController.findOneGiveKanbanDemand(item, wareHouseId, function(err, records) {
        if (err) {
            deferred.reject(err);
            return;
        }
        if (records.length === 0) {
            deferred.resolve([]);
            return;
        }
        var results = [],
            batches = [];
        _.forEach(records, function(record) {
            batches.push(queryDemandDetail(item, record, results));
        });
        Q.all(batches).then(function() {
            deferred.resolve(results);
        }, function(err) {
            deferred.reject(err);
        });
    });

    return deferred.promise;
}

function queryDemandDetail(itemMaterObj, kanbanDemand, results) {
    var deferred = Q.defer();

    var _stockQty = 0;
    rcvRecordController.queryStockQty(
        kanbanDemand.WareHouse, itemMaterObj.ItemMaster, itemMaterObj.DescSeg1, itemMaterObj.DescSeg2
    ).then(function(stockQty) {
        _stockQty = stockQty;
        return querydepartmentName(kanbanDemand.DemandDepartment);
    }).then(function(resultDepartment) {
        results.push({
            CreatedOn: kanbanDemand.CreatedOn,
            ItemMasterCode: kanbanDemand.ItemMaster.Code,
            ItemMasterName: kanbanDemand.ItemMaster.Name,
            DescSeg1: itemMaterObj.DescSeg1,
            DescSeg2: itemMaterObj.DescSeg2,
            DemandQty: kanbanDemand.TotalDemandQty - kanbanDemand.TotalReceiveQty,
            NeedQty: kanbanDemand.TotalDemandQty - kanbanDemand.TotalReceiveQty - _stockQty,
            RcvQty: itemMaterObj.Num,
            TotalDemandQty: kanbanDemand.TotalDemandQty,
            TotalStockQty: _stockQty,
            TotalReceiveQty: kanbanDemand.TotalReceiveQty,
            DemandDepartment: resultDepartment.Name
        });
        deferred.resolve();
    }).catch(function(err) {
        deferred.resolve();
    });

    return deferred.promise;
}
//通过部门id查询部门名称的方法
function querydepartmentName(DemandDepartment) {
    var deferred = Q.defer();
    var data = {};
    departmentController.findDepartmentById(DemandDepartment, function(departmentErr, departmentResult) {
        if (departmentErr) {
            deferred.reject(err);
        } else {
            if (departmentResult) {
                data = {
                    Name: departmentResult.Name
                };
                deferred.resolve(data);
            }
        }
    });
    return deferred.promise;
}
//获取上游看板需求
exports.GetUpStreamKanban = function(req, res) {
    var parameter = req.body.Parameter,
        userId = parameter.userId;
    getConnectArea(userId, true).then(function(connectArea) {
        if (!connectArea) {
            res.json({
                Data: null,
                Error: "该用户下没有对应的交接区，请添加相应的交接区信息。"
            });
            return;
        }
        Q.all([
            getRvRecordsByConnectArea(connectArea._id),
            getKanbanDemand({
                ConnectArea: connectArea._id,
                $where: "this.TotalDemandQty - this.TotalStockQty > 0"
            })
        ]).spread(function() {
            if (arguments.length < 2) {
                res.json({
                    Data: null,
                    Error: "通过交接区ID未查到入库记录或者没有满足的看板需求记录."
                });
                return;
            }
            var rvRecords = arguments[0],
                demands = arguments[1],
                kanban = [];
            _.forEach(rvRecords, function(rvRecord) {
                _.forEach(demands, function(demand) {
                    if (rvRecord._id.toString() == demand.MO.toString()) {
                        kanban.push({
                            Priority: demand.Priority == undefined ? 0 : demand.Priority,
                            NOLotNumber: rvRecord.value.barcode.MOLotNumber == undefined ? '' : rvRecord.value.barcode.MOLotNumber,
                            ItemMasterCode: rvRecord.value.barcode.ItemMasterCode == undefined ? '' : rvRecord.value.barcode.ItemMasterCode,
                            ItemMasterName: rvRecord.value.barcode.ItemMasterName == undefined ? '' : rvRecord.value.barcode.ItemMasterName,
                            TotalDemandQty: demand.TotalDemandQty == undefined ? 0 : demand.TotalDemandQty,
                            TotalNeedQty: (demand.TotalDemandQty - demand.TotalStockQty) == undefined ? 0 : (demand.TotalDemandQty - demand.TotalStockQty),
                            RcvQty: rvRecord.value.RcvQty == undefined ? 0 : rvRecord.value.RcvQty,
                            TotalStockQty: demand.TotalStockQty == undefined ? 0 : demand.TotalStockQty,
                            TotalReceiveQty: demand.TotalReceiveQty == undefined ? 0 : demand.TotalReceiveQty
                        });
                    }
                });
            });
            res.json({
                Data: kanban,
                Error: null
            });
        });
    });

};
//获取下游看板需求
exports.GetDownStreamKanban = function(req, res) {
    var parameter = req.body.Parameter,
        userId = parameter.userId;
    //入库记录(批次(工单)-库存)
    getConnectArea(userId, false).then(function(connectArea) {
        if (!connectArea) {
            res.json({
                Data: null,
                Error: "该用户下没有对应的交接区，请添加相应的交接区信息。"
            });
            return;
        }
        Q.all([
            getRvRecordsByConnectArea(connectArea._id),
            getKanbanDemand({
                ConnectArea: connectArea._id,
                $where: "this.TotalDemandQty - this.TotalReceiveQty > 0"
            })
        ]).spread(function() {
            if (arguments.length < 2) {
                res.json({
                    Data: null,
                    Error: "通过交接区ID未查到入库记录或者没有满足的看板需求记录."
                });
                return;
            }
            var rvRecords = arguments[0],
                demands = arguments[1],
                kanban = [];
            _.forEach(rvRecords, function(rvRecord) {
                _.forEach(demands, function(demand) {
                    if (rvRecord._id.toString() == demand.MO.toString()) {
                        kanban.push({
                            Priority: demand.Priority == undefined ? 0 : demand.Priority,
                            NOLotNumber: rvRecord.value.barcode.MOLotNumber == undefined ? '' : rvRecord.value.barcode.MOLotNumber,
                            ItemMasterCode: rvRecord.value.barcode.ItemMasterCode == undefined ? '' : rvRecord.value.barcode.ItemMasterCode,
                            ItemMasterName: rvRecord.value.barcode.ItemMasterName == undefined ? '' : rvRecord.value.barcode.ItemMasterName,
                            RcvQty: rvRecord.value.RcvQty == undefined ? 0 : rvRecord.value.RcvQty,
                            TotalReceiveQty: demand.TotalReceiveQty == undefined ? 0 : demand.TotalReceiveQty,
                            NeedDeliveryQty: (demand.TotalDemandQty - demand.TotalReceiveQty) == undefined ? 0 : (demand.TotalDemandQty - demand.TotalReceiveQty)
                        });
                    }
                });
            });
            res.json({
                Data: kanban,
                Error: null
            });
        }, function(err) {
            res.json({
                Data: null,
                Error: err
            });
        });
    });
};

//交接区检货UdpatePIckUpQty,确认服务
//交接检查是获取球拍的检查状态、重复扫描的合规性
exports.getBarcodeMasterInfo = function(req, res) {
    var parameter = req.body.Parameter,
        Barcode = parameter.Barcode;
    var entityRcvRecord = entityCollection.getEntity("RcvRecord"),
        entityBarcodeMaster = entityCollection.getEntity("BarcodeMaster");
    //现根据芯片ID检查入库记录，做重复扫描的合规性检查
    entityRcvRecord.findOne({
        Barcode: Barcode
    }, null, function(err, record) {
        if (err) {
            res.json({
                Data: null,
                Error: err
            });
            return;
        }
        if (!record) {
            res.json({
                Data: "此球拍没有做入库或这是重复扫描",
                Error: null
            });
        } else {
            //接收芯片对应的条码主档
            entityBarcodeMaster.findOne({
                Barcode: Barcode
            }, null, function(err, record) {
                if (err) {
                    res.json({
                        Data: null,
                        Error: err
                    });
                    return;
                }
                res.json({
                    Data: record,
                    Error: null
                });
            });
        }
    });
};
//通过用户ID获取交接区信息,flag == true(上游)，flag == false(下游)
function getConnectArea(userId, flag) {
    var deferred = Q.defer();
    var userModel = mongoose.model('User');
    //通过用户ID获取部门
    userModel.findOne({
        _id: userId
    }, {
        Department: 1
    }).exec(function(err, record) {
        if (err) {
            deferred.reject(err);
        }

        if (!record) {
            deferred.reject("用户对应部门为空");
        }
        var queryCondition = {};
        if (flag) {
            queryCondition = {
                UpDepartment: record.Department
            };
        } else {
            queryCondition = {
                DownDepartment: record.Department
            };
        }
        //通过用户部门获取交界区
        var entity = entityCollection.getEntity("WareHouse");
        entity.findOne(queryCondition, null, function(err, result) {
            if (err) {
                deferred.reject(err);
            } else {
                deferred.resolve(result);
            }
        });
    });
    return deferred.promise;
}
//根据芯片ID(Barcode)，分组key,获取条码主档[key,value]  ----没有查到使用
function queryByBarcodeAndGroupByMo(key, barcodeList) {
    var deferred = Q.defer();
    var entityBarcodeMaster = entityCollection.getEntity("BarcodeMaster");
    entityBarcodeMaster.aggregateCount(key, {
        Barcode: {
            $in: barcodeList
        }
    }, function(err, data) {
        if (err) {
            deferred.reject(err);
        }
        deferred.resolve(data);
    });
    return deferred.promise;
}
//根据交界区ID取得看板
function getKanbanDemand(condition) {
    var deferred = Q.defer();
    var entity = entityCollection.getEntity("KanbanDemand");
    entity.find(condition, null, null, function(err, results) {
        if (err) {
            deferred.reject(err);
        } else {
            deferred.resolve(results);
        }
    });
    return deferred.promise;
}
//根据交接区ID获取入库记录
function getRvRecordsByConnectArea(connectAreaId) {
    var deferred = Q.defer();
    var entity = entityCollection.getEntity("RcvRecord");

    var barcodeMap = function() {
        emit(this.BusinessDocID, {
            barcode: this.BarcodeMaster,
            RcvQty: this.RcvQty
        });
    };

    var reduce = function(key, values) {
        return {
            barcode: this.BarcodeMaster,
            RcvQty: Array.sum(values.RcvQty)
        }
    };

    var query = {
        //connectAreaId: connectAreaId,
        //Location: null
    };

    var option = {
        map: barcodeMap,
        reduce: reduce,
        query: query
    };

    entity.mapReduce(option, function(err, results) {
        var barcodeModel = mongoose.model('BarcodeMaster');
        barcodeModel.populate(results, {
            path: 'value.barcode'
        }, function(err, resultsBarcodes) {
            deferred.resolve(resultsBarcodes);
        });
    });

    return deferred.promise;
}
//根据芯片ID(Barcode)获取入库记录
function getRcvRecordsByBarcode(barcodeList) {
    var deferred = Q.defer();
    var entity = entityCollection.getEntity("RcvRecord");
    entity.find({
        Barcode: {
            $in: barcodeList
        }
    }, null, null, function(err, records) {
        if (err) {
            deferred.reject(err);
        } else {
            deferred.resolve(records);
        }
    });
    return deferred.promise;
}

function BatchSaveByTran(array) {
    var deferred = Q.defer();
    Transaction.BatchSaveByTran(array, function(err, result) {
        if (err) {
            deferred.reject(err);
        } else {
            deferred.resolve(result);
        }
    });
    return deferred.promise;

}

/**
 * 交接检查交接确认专属服务
 * jiadx
 **/
// 通过仓库ID获取所有部门
exports.getAllDepartment = function(req, res) {
    var parameter = req.body.Parameter,
        wareHouseId = parameter.wareHouseId,
        condition = {};

    if (wareHouseId) {
        condition.WareHouse = wareHouseId
    }
    kanbanDemandController.queryDemandByWareHouse(condition, function(err, records) {
        if (err) {
            res.json({
                Data: null,
                Error: err
            });
        } else {
            res.json({
                Data: records,
                Error: null
            });
        }
    });
};
// 根据芯片查找容器
exports.queryBarcodeMasterInfo = function(req, res) {
    var body = req.body,
        Barcode = body.Barcode,
        flg = body.flg;
    var entity = entityCollection.getEntity("BarcodeMaster");
    entity.findOne({
        Barcode: Barcode
    }, null, function(err, record) {
        if (err) {
            var newErr = new Error();
            newErr.leval = 9;
            newErr.title = '查询芯片失败';
            newErr.message = '未识别的芯片，请重新扫描';
            res.json({
                Data: null,
                Error: newErr
            });
            return;
        }
        if (record === null) {
            var newErr = new Error();
            newErr.leval = 9;
            newErr.title = '查询芯片失败';
            newErr.message = '未查到容器，请更换芯片';
            res.json({
                Data: null,
                Error: newErr
            });
            return;
        }
        if (record.BarcodeType === 3) {
            ContainerController.getContainerById(record.EntityID, function(err, result) {
                if (err) {
                    var newErr = new Error();
                    newErr.leval = 9;
                    newErr.title = '查询芯片失败';
                    newErr.message = '未识别的芯片，请重新扫描';
                    res.json({
                        Data: null,
                        Error: newErr
                    });
                    return;
                }
                if (flg === 'checkUp') {
                    getDeliveryRecord(result._id).then(function(length) {
                        if (length > 0) {
                            var newErr = new Error();
                            newErr.leval = 9;
                            newErr.title = '重复提交';
                            newErr.message = '存在未确认的配送记录!';
                            res.json({
                                Data: null,
                                Error: newErr
                            });
                            return;
                        }
                        res.json({
                            Data: {
                                Barcode: Barcode,
                                _id: result._id,
                                Code: result.Code,
                                Name: result.Name,
                                UniqueID: result.UniqueID
                            },
                            Error: null
                        });
                    }, function() {
                        var newErr = new Error();
                        newErr.leval = 9;
                        newErr.title = '查询物流配送失败';
                        newErr.message = '查询物流配送失败';
                        res.json({
                            Data: null,
                            Error: newErr
                        });
                    });
                } else {
                    res.json({
                        Data: {
                            Barcode: Barcode,
                            _id: result._id,
                            Code: result.Code,
                            Name: result.Name,
                            UniqueID: result.UniqueID
                        },
                        Error: null
                    });
                }
            });
        } else {
            var newErr = new Error();
            newErr.leval = 9;
            newErr.title = '查询容器失败';
            newErr.message = '芯片对应的不是容器';
            res.json({
                Data: null,
                Error: newErr
            });
        }
    });
};
// 根据容器查找仓库
exports.getWareHouseByContainer = function(req, res) {
    var parameter = req.body.Parameter,
        containerId = parameter.containerId,
        demandDepartmentId =parameter.demandDepartmentId;
    DeliveryRecordController.queryWareHouseByContainer(containerId,demandDepartmentId, function(err, record) {
        if (err || record === null) {
            var newErr = new Error();
            newErr.leval = 9;
            newErr.title = '查询待配送记录失败';
            newErr.message = '未找到待配送记录！';
            res.json({
                Data: null,
                Error: newErr
            });
        } else {
            res.json({
                Data: record,
                Error: null
            });
        }
    });
};
// 查找到所有仓库
exports.getAllWareHouse = function(req, res) {
    connectAreaController.getAllWareHouse(function(err, result) {
        if (err) {
            res.json({
                Data: null,
                Error: err
            });
        } else {
            if (result == null) {
                var newErr = new Error();
                newErr.leval = 9;
                newErr.title = '查询仓库失败';
                newErr.message = '未找到对应的仓库！';
                res.json({
                    Data: null,
                    Error: newErr
                });
            } else {
                res.json({
                    Data: result,
                    Error: null
                });
            }
        }
    });

};
// 校验物料是否合规
exports.checkCompliance = function(req, res) {
    var body = req.body,
        barcode = body.Barcode,
        wareHouseId = body.WareHouseId,
        departmentId = body.DepartmentId;
    var barcodeInfo = {};
    checkBarcodeQCStatus(barcode).then(function(result) {
        barcodeInfo = {
            _id: result._id,
            Barcode: result.Barcode,
            QCStatus: result.QCStatus,
            ItemMaster: result.ItemMaster._id,
            ItemMasterCode: result.ItemMasterCode,
            ItemMasterName: result.ItemMasterName,
            DescSeg1: result.DescSeg1,
            DescSeg2: result.DescSeg2
        };
        return isCutTheMustard(barcodeInfo, wareHouseId, departmentId);
    }).then(function(rel) {
        barcodeInfo.TotalDemandQty = rel.TotalDemandQty;
        barcodeInfo.TotalStockQty = rel.TotalStockQty;
        barcodeInfo.TotalReceiveQty = rel.TotalReceiveQty;
        barcodeInfo.stockQty = rel.stockQty;
        return rcvRecordIsExistsBarcode(barcodeInfo, wareHouseId);
    }).then(function(record) {
        barcodeInfo.RcvDateTime = record.RcvDateTime;
        res.json({
            Data: barcodeInfo,
            Error: null
        });
    }).catch(function(err) {
        BaseFun.errorLog('交接检查' + err.title, err.message, "芯片ID：" + barcode);
        res.json({
            Data: null,
            Error: err
        });
    }).done();
};
// 获取检查之外的看板需求
exports.getKanBanDetail = function(req, res) {
    var body = req.body,
        demandDepartment = body.demandDepartment,
        scanArrlist = body.scanArrlist;
    kanbanDemandController.queryDemandByDepartment(demandDepartment, function(err, records) {
        if (err) {
            res.json({
                Data: null,
                Error: err
            });
            return;
        }
        var task = [],
            resultObj = {};
        _.forEach(records, function(record) {
            task.push(queryLotsStockQty(record.WareHouse, record.ItemMaster._id, record.DescSeg1, record.DescSeg2, record, scanArrlist, resultObj));
        });
        Q.all(task).then(function() {
            res.json({
                Data: resultObj,
                Error: null
            });
        }, function(err) {
            res.json({
                Data: null,
                Error: err
            });
        });
    });
};
// 根据容器和仓库查找入库记录
exports.queryByContainerAndWareHouse = function(req, res) {
    var body = req.body,
        WareHouse = body.wareHouseId,
        Container = body.containerId;
    rcvRecordController.queryByContainerAndWareHouse(WareHouse, Container, function(err, records) {
        if (err) {
            var error = new Error();
            error.title = '查询入库记录错误';
            error.message = '查询入库记录错误！';
            res.json({
                Data: null,
                Error: error
            });
            return;
        }
        if (records.length === 0) {
            var error = new Error();
            error.title = '未查到入库记录';
            error.message = '未查到入库记录！';
            res.json({
                Data: null,
                Error: error
            });
            return;
        }
        var obj = {},
            barcodeArr = [];
        _.forEach(records, function(record) {
            if (record.BarcodeMaster) {
                var key = record.BarcodeMaster.ItemMasterCode + '-' + (record.BarcodeMaster.DescSeg1 ? record.BarcodeMaster.DescSeg1 : '空') + '-' + (record.BarcodeMaster.DescSeg2 ? record.BarcodeMaster.DescSeg2 : '空');
                if (!obj[key]) {
                    obj[key] = {
                        key: key,
                        ItemMaster: record.BarcodeMaster.ItemMaster,
                        DescSeg1: record.BarcodeMaster.DescSeg1,
                        DescSeg2: record.BarcodeMaster.DescSeg2,
                        scanNum: 1
                    };
                } else {
                    obj[key].scanNum += 1;
                }
                barcodeArr.push(record.Barcode);
            } else {
                BaseFun.errorLog("入库关联主档错误", "入库记录关联到对应的主档", record.Barcode);
            }
        });
        res.json({
            Data: {
                obj: obj,
                barcodeArr: barcodeArr
            },
            Error: null
        });

    });
};
// 交接检查确认服务
exports.checkUp = function(req, res) {
    var body = req.body,
        userId = body.userId,
        wareHouseId = body.wareHouseId,
        validBarcode = body.validBarcode,
        containerId = body.containerId,
        departmentId = body.departmentId;
    getDeliveryRecord(containerId).then(function(length) {
        if (length > 0) {
            var newErr = new Error();
            newErr.leval = 9;
            newErr.title = '重复提交';
            newErr.message = '配送记录已生成，请勿重复提交!';
            res.json({
                Data: null,
                Error: newErr
            });
            return;
        }
        getRcvRecordsByBarcode(validBarcode).then(function(rcvRecords) {
            var deliveryRecord = [],
                rcvRecord = [];
            deliveryRecord.push({
                WareHouse: wareHouseId,
                DemandDepartment: departmentId,
                Container: containerId,
                Status: 0,
                Qty: validBarcode.length,
                ReadyTime: new Date(),
                StockPerson: userId,
                RowStatus: BaseEnum.RowStatus.Insert.Value
            });
            _.forEach(rcvRecords, function(rev) {
                rev.Container = containerId;
                rev.RowStatus = BaseEnum.RowStatus.Modify.Value;
                rev.SysVersion = rev.SysVersion;
                rcvRecord.push(rev);
            });
            BatchSaveByTran([{
                EntityName: 'RcvRecord',
                Records: rcvRecord
            }, {
                EntityName: 'DeliveryRecord',
                Records: deliveryRecord
            }]).then(function(result) {
                BaseFun.errorLog("交接检查成功", JSON.stringify(rcvRecord)+JSON.stringify(deliveryRecord), "容器ID：" + containerId.toString());
                SocketIo.emit(wareHouseId.toString(), '');
                res.json({
                    Data: result,
                    Error: null
                });
            }, function(err) {
                BaseFun.errorLog(err.title, err.message, "容器ID：" + containerId.toString());
                res.json({
                    Data: null,
                    Error: err
                });
            });
        });
    }, function(err) {
        res.json({
            Data: null,
            Error: err
        });
    });

};
// 通过条码主档对应的质检状态判断
function checkBarcodeQCStatus(barcode) {
    var deferred = Q.defer(),
        errCallRes = new Error();
    errCallRes.leval = 9;
    barcodeMasterController.findBarcodeMaster(barcode, function(err, result) {
        if (err) {
            errCallRes.title = '查询物料错误';
            errCallRes.flag = 9; //9无法统计
            errCallRes.message = '无法识别的芯片，请重新扫描！';
            errCallRes.obj = undefined;
            deferred.reject(errCallRes);
            return;
        }
        if (result === null) {
            errCallRes.title = '查询物料错误';
            errCallRes.flag = 9; //9无法统计
            errCallRes.message = '没有对应的物料！';
            errCallRes.obj = undefined;
            deferred.reject(errCallRes);
            return;
        }
        if (result === null) {
            errCallRes.title = '查询物料错误';
            errCallRes.flag = 9; //9无法统计
            errCallRes.message = '未找到物料，请更换芯片！';
            errCallRes.obj = undefined;
            deferred.reject(errCallRes);
            return;
        }
        if (result.BarcodeType === null || result.BarcodeType !== 0) {
            errCallRes.title = '查询物料错误';
            errCallRes.flag = 9; //9无法统计
            errCallRes.message = '芯片对应的不是物料，请重新扫描!';
            errCallRes.obj = undefined;
            deferred.reject(errCallRes);
            return;
        }
        if (result.QCStatus === undefined && result.QCStatus === '') {
            errCallRes.title = '芯片的质检状态异常';
            errCallRes.flag = 0; //红色圈,0的标志
            errCallRes.message = '芯片没有质检状态!';
            errCallRes.obj = result;
            deferred.reject(errCallRes);
            return;
        }

        ExtendEnumFunction.getExtendEnum('QCStatus', function(err, record) {
            if (err) {
                errCallRes.title = '查询质检状态失败';
                errCallRes.flag = 9; //9无法统计
                errCallRes.message = '查询质检状态失败!';
                errCallRes.obj = undefined;
                deferred.reject(errCallRes);
                return;
            }
            var enumObj = {};
            _.forEach(record, function(option) {
                if (!enumObj[option.Value]) {
                    enumObj[option.Value] = option.Text;
                }
            });
            if (result.QCStatus !== 0 && result.QCStatus !== 2) {
                errCallRes.title = '芯片的质检状态异常';
                errCallRes.flag = 0; //红色圈,0的标志
                errCallRes.obj = result;
                if (enumObj[result.QCStatus]) {
                    errCallRes.message = '质检状态为' + enumObj[result.QCStatus] + '!';
                } else {
                    errCallRes.message = '质检状态没在系统中预设!';
                }
                deferred.reject(errCallRes);
            } else {
                deferred.resolve(result);
            }
        });
    });
    return deferred.promise;
}
// 查询某一芯片是否入库
function rcvRecordIsExistsBarcode(barcodeInfo, wareHouseId) {
    var deferred = Q.defer();
    var errCallRes = new Error();
    errCallRes.leval = 9;
    rcvRecordController.getRcvRecordByBarcodeMasterAndWareHouseId(barcodeInfo._id, wareHouseId, function(err, result) {
        if (err) {
            errCallRes.title = '查询记录错误';
            errCallRes.flag = 9; //9无法统计
            errCallRes.message = '无法识别的芯片，请重新扫描！';
            errCallRes.obj = undefined;
            deferred.reject(errCallRes);
            return;
        }
        if (result) {
            deferred.resolve(result);
        } else {
            errCallRes.title = '芯片未入库';
            errCallRes.flag = 1; //灰色圈,1的标志
            errCallRes.message = '芯片未入当前库!';
            errCallRes.obj = barcodeInfo;
            deferred.reject(errCallRes);
        }
    });
    return deferred.promise;
}
// 型号，尺寸外观，仓库，部门查找
function isCutTheMustard(barcodeInfo, wareHouseId, departmentId) {
    var deferred = Q.defer();
    var errCallRes = new Error();
    errCallRes.leval = 9;
    kanbanDemandController.findOneKanbanDemand(barcodeInfo, wareHouseId, departmentId, function(err, result) {
        if (err) {
            errCallRes.title = '查询看板记录错误';
            errCallRes.flag = 9; //9无法统计
            errCallRes.message = '查询看板记录错误！';
            deferred.reject(errCallRes);
            errCallRes.obj = undefined;
            return;
        }
        if (result) { //型号尺寸外观能够查出一条，则进行查询需求数量
            queryStockQty(wareHouseId, barcodeInfo.ItemMaster, barcodeInfo.DescSeg1, barcodeInfo.DescSeg2).then(function(qty) {
                deferred.resolve({
                    TotalDemandQty: result.TotalDemandQty,
                    TotalStockQty: result.TotalStockQty, //不使用
                    TotalReceiveQty: result.TotalReceiveQty,
                    stockQty: qty
                });
            }, function() {
                errCallRes.title = '查询入库记录错误';
                errCallRes.flag = 9; //9无法统计
                errCallRes.message = '查询入库记录错误！';
                errCallRes.obj = undefined;
                deferred.reject(errCallRes);
            });
        } else {
            errCallRes.title = '型号不匹配';
            errCallRes.flag = 1; //灰色圈,1的标志
            errCallRes.message = '型号不匹配!';
            _.merge(barcodeInfo, {
                TotalDemandQty: 0,
                TotalStockQty: 0,
                TotalReceiveQty: 0,
                stockQty: 0
            });
            errCallRes.obj = barcodeInfo;
            deferred.reject(errCallRes);
        }

    });
    return deferred.promise;
}
// 查询入库数量
function queryStockQty(wareHouseId, itemMasterId, sizeType, appearance) {
    var deferred = Q.defer();
    rcvRecordController.queryStockQty(wareHouseId, itemMasterId, sizeType, appearance).then(function(stockQty) {
        deferred.resolve(stockQty);
    }, function(err) {
        deferred.reject(err);
    });
    return deferred.promise;
}
// 检查扫描结束后查询入库数量
function queryLotsStockQty(wareHouseId, itemMasterId, sizeType, appearance, record, scanArrlist, resultObj) {
    var deferred = Q.defer();
    rcvRecordController.queryStockQty(wareHouseId, itemMasterId, sizeType, appearance).then(function(stockQty) {
        var key = record.ItemMaster.Code + '-' + (record.DescSeg1 ? record.DescSeg1 : '空') + '-' + (record.DescSeg2 ? record.DescSeg2 : '空');
        if (!scanArrlist.hasOwnProperty(key)) {
            resultObj[key] = {
                key: key,
                reqNum: record.TotalDemandQty - record.TotalReceiveQty - stockQty,
                scanNum: 0,
                ItemMaster: record.ItemMaster._id,
                ItemMasterCode: record.ItemMaster.Code,
                Size: sizeType,
                Skin: appearance
            }
        }
        deferred.resolve();
    }, function(err) {
        deferred.reject(err);
    });
    return deferred.promise;
}
//通过配送记录限制交接检查重复提交
function getDeliveryRecord(containerId) {
    var deferred = Q.defer();
    DeliveryRecordController.queryByCondition({
        Container: containerId,
        Status: 0,
        $or: [{
            ReceiveQty: {
                $exists: false
            }
        }, {
            ReceiveQty: 0
        }]
    }, function(err, record) {
        if (err) {
            deferred.reject(err);
        } else {
            deferred.resolve(record.length);
        }
    });
    return deferred.promise;
}
// 交接确认确认服务
exports.confirmDown = function(req, res) {
    var body = req.body,
        userId = body.userId,
        TerminalId = body.TerminalId,
        TerminalName = body.TerminalName,
        WorkId = body.WorkId,
        WorkName = body.WorkName,
        WorkLocationId = body.WorkLocationId,
        WorkLocationName = body.WorkLocationName,

        dataObj = body.dataObj,
        barcodeList = body.barcodeList,
        containerId = body.containerId,
        wareHouseId = body.wareHouseId,
        departmentId = body.departmentId;
    var BarcodeRecords, OperationRecord, barcodeUp = [],
        bizRecords = [],
        rcvRecords = [],
        kanbans = [],
        rcvRecordDel = [],
        delivertUp = [],
        IsStoragePoint = false;
    getDeliveryRecord(containerId).then(function(length) {
        if (length === 0) {
            var newErr = new Error();
            newErr.leval = 9;
            newErr.title = '重复提交';
            newErr.message = '配送记录已更新，请勿重复提交!';
            return Q.reject(newErr);
        }
        return findBarcodeMaster(barcodeList);
    }).then(function(BarcodeResults) {
        BarcodeRecords = BarcodeResults;
        return findOperation(BarcodeResults[0].ItemMaster, WorkId);
    }).then(function(operationResult) {
        OperationRecord = operationResult;
        _.forEach(BarcodeRecords, function(barcode) {
            var bizRecord = {
                _id: BaseFun.getObjectId(),
                BarcodeMaster: barcode._id,
                CollectDateTime: Date.now(),
                Terminal: TerminalId,
                TerminalName: TerminalName,
                Work: WorkId,
                WorkName: WorkName,
                Operation: operationResult._id || null,
                OperationName: operationResult.Name || null,
                WorkLocation: WorkLocationId,
                WorkLocationName: WorkLocationName,
                Users: [userId],
                RowStatus: BaseEnum.RowStatus.Insert.Value
            };
            bizRecords.push(bizRecord);
            if (OperationRecord.OperationFlg && OperationRecord.OperationFlg.IsStoragePoint) {
                var rcvRecord = {
                    _id: BaseFun.getObjectId(),
                    BarcodeMaster: barcode._id,
                    Barcode: barcode.Barcode,
                    ItemMaster: barcode.ItemMaster || null,
                    DescSeg1: barcode.DescSeg1 || null,
                    DescSeg2: barcode.DescSeg2 || null,
                    RcvOperation: OperationRecord._id,
                    OperationFlg: OperationRecord,
                    BusinessDocID: barcode.MO || null,
                    RcvUser: [userId],
                    BizRecord: bizRecord._id,
                    RcvDateTime: bizRecord.CollectDateTime,
                    RowStatus: BaseEnum.RowStatus.Insert.Value
                };
                rcvRecords.push(rcvRecord);
            }
            barcodeUp.push({
                _id: barcode._id,
                Operation: bizRecord.Operation,
                OperationName: bizRecord.OperationName,
                Work: bizRecord.Work,
                WorkName: bizRecord.WorkName,
                WorkLocation: bizRecord.WorkLocation,
                WorkLocationName: bizRecord.WorkLocationName,
                Users: bizRecord.Users,
                BizRecord: bizRecord._id,
                SysVersion: barcode.SysVersion,
                RowStatus: BaseEnum.RowStatus.Modify.Value
            });
        });
        BaseFun.errorLog("交接确认-barcodeUp+rcvRecord", JSON.stringify(bizRecords)+JSON.stringify(barcodeUp), "容器ID：" + containerId.toString());
        if (OperationRecord.OperationFlg && OperationRecord.OperationFlg.IsStoragePoint) {
            return findWareHouse(departmentId);
        } else {
            return Q.resolve();
        }
    }).then(function(nextWareHouse) {
        if (OperationRecord.OperationFlg && OperationRecord.OperationFlg.IsStoragePoint) {
            _.forEach(rcvRecords, function(rcvRecord) {
                _.merge(rcvRecord, {
                    WareHouse: nextWareHouse._id
                });
            });
            IsStoragePoint = true;
        }
        var task = [];
        task.push(findKanbanInfo({
            WareHouse: wareHouseId,
            DemandDepartment: departmentId
        }));
        task.push(findRcvRecordInfo(barcodeList, containerId));
        task.push(findDeliveryRecord(containerId));
        return Q.all(task);
    }).then(function(taskResult) {
        var kanbanObj = {};
        _.forEach(taskResult[0], function(kanban) {
            var key = kanban.ItemMaster.Code + '-';
            if (!kanban.DescSeg1 || kanban.DescSeg1 === '') {
                key += '空';
            } else {
                key += kanban.DescSeg1;
            }
            key += '-';
            if (!kanban.DescSeg2 || kanban.DescSeg2 === '') {
                key += '空';
            } else {
                key += kanban.DescSeg2;
            }
            if (!kanbanObj[key]) {
                kanbanObj[key] = kanban;
            }
        });
        _.forEach(dataObj, function(obj) {
            if (kanbanObj.hasOwnProperty(obj.key)) {
                kanbans.push({
                    _id: kanbanObj[obj.key]._id,
                    TotalReceiveQty: (kanbanObj[obj.key].TotalReceiveQty + obj.scanNum),
                    SysVersion: kanbanObj[obj.key].SysVersion,
                    RowStatus: BaseEnum.RowStatus.Modify.Value
                });
            }
        });
        BaseFun.errorLog("交接确认-kanbans", JSON.stringify(kanbans), "容器ID：" + containerId.toString());
        _.forEach(taskResult[1], function(rcv) {
            rcvRecordDel.push({
                _id: rcv._id,
                RowStatus: BaseEnum.RowStatus.Delete.Value
            });
        });
        BaseFun.errorLog("交接确认-rcvRecordDel", JSON.stringify(rcvRecordDel), "容器ID：" + containerId.toString());
        delivertUp.push({
            _id: taskResult[2][0]._id,
            Status: 2,
            ReceiveQty: barcodeList.length,
            ReceiveTime: new Date(),
            ReceivePerson: userId,
            SysVersion: taskResult[2][0].SysVersion,
            RowStatus: BaseEnum.RowStatus.Modify.Value
        });
        BaseFun.errorLog("交接确认-delivertUp", JSON.stringify(delivertUp), "容器ID：" + containerId.toString());
        var array= [
         {EntityName: 'BizRecord',Records: bizRecords},
         {EntityName: 'RcvRecord',Records: rcvRecordDel},
         {EntityName: 'KanbanDemand',Records: kanbans},
         {EntityName: 'DeliveryRecord',Records: delivertUp},
         {EntityName: 'BarcodeMaster',Records: barcodeUp}];
        if (IsStoragePoint) {
             array.push({EntityName: 'RcvRecord',  Records: rcvRecords});
            return finishConfirm(array,wareHouseId,containerId);
        } else {
            return finishConfirm(array,wareHouseId,containerId);
        }
    }).then(function(finishResult) {
        res.json({
            Data: finishResult,
            Error: null
        });
    }).catch(function(err) {
        BaseFun.errorLog(err.title, err.message, "容器ID：" + containerId.toString());
        res.json({
            Data: null,
            Error: err
        });
    }).done();
};

function findBarcodeMaster(barcodeList) {
    var deferred = Q.defer();
    barcodeMasterController.findBarcodeMasters(barcodeList).then(function(records) {
        deferred.resolve(records);
    }, function(err) {
        var newErr = new Error();
        newErr.leval = 9;
        newErr.title = '查询主档失败';
        newErr.message = '查询主档记录失败！';
        deferred.reject(newErr);
    });
    return deferred.promise;
}

function findOperation(itemMaster, work) {
    var deferred = Q.defer();

    operationController.findByItemMasterAndWork(itemMaster, work, function(err, result) {
        if (err) {
            var newErr = new Error();
            newErr.leval = 9;
            newErr.title = '查询工序失败';
            newErr.message = '查询工序失败！';
            deferred.reject(newErr);
            return;
        }
        if (result === null) {
            var newErr = new Error();
            newErr.leval = 9;
            newErr.title = '未查询到工序';
            newErr.message = '未查询到对应工序！';
            deferred.reject(newErr);
            return;
        }
        deferred.resolve(result);
    });

    return deferred.promise;
}

function writeBizRecord(bizRecords) {
    var deferred = Q.defer();
    bizRecordController.addBizRecords(bizRecords, function(err, result) {
        if (err) {
            var newErr = new Error();
            newErr.leval = 9;
            newErr.title = '插入流水';
            newErr.message = '批量写入流水失败！';
            deferred.reject(newErr);
        } else {
            deferred.resolve(result);
        }
    });
    return deferred.promise;
}

function findWareHouse(departmentId) {
    var deferred = Q.defer();
    wareHouseController.findByDepartmentDeep(departmentId).then(function(wareHouse) {
        if (wareHouse === null) {
            var newErr = new Error();
            newErr.leval = 9;
            newErr.title = '查询仓库失败';
            newErr.message = '未查询到对应的仓库！';
            deferred.reject(newErr);
            return;
        }
        deferred.resolve(wareHouse);
    }, function(err) {
        var newErr = new Error();
        newErr.leval = 9;
        newErr.title = '查询仓库失败';
        newErr.message = '查询对应的仓库失败！';
        deferred.reject(newErr);
    });
    return deferred.promise;
}

function addStockQty(rcvRecords) {
    var deferred = Q.defer();
    rcvRecordController.addStockQty(rcvRecords).then(function(data) {
        deferred.resolve(data);
    }, function(err) {
        var newErr = new Error();
        newErr.leval = 9;
        newErr.title = '入库失败';
        newErr.message = '入库失败！';
        deferred.reject(newErr);
    });
    return deferred.promise;
}

function findKanbanInfo(condition) {
    var deferred = Q.defer();
    kanbanDemandController.findRecordsByCondition(condition, function(err, records) {
        if (err) {
            var newErr = new Error();
            newErr.leval = 9;
            newErr.title = '获取看板失败';
            newErr.message = '获取看板失败！';
            deferred.reject(newErr);
        }
        if (records.length === 0) {
            var newErr = new Error();
            newErr.leval = 9;
            newErr.title = '获取看板失败';
            newErr.message = '未查询到看板！';
            deferred.reject(newErr);
            return;
        }
        deferred.resolve(records);
    });
    return deferred.promise;
}

function findRcvRecordInfo(Barcodes, containerId) {
    var deferred = Q.defer();
    rcvRecordController.queryByCondition({
        Barcode: {
            $in: Barcodes
        },
        Container: containerId
    }, function(err, results) {
        if (err) {
            var newErr = new Error();
            newErr.leval = 9;
            newErr.title = '查询入库记录失败';
            newErr.message = '查询入库记录失败！';
            deferred.reject(newErr);
            return;
        }
        if (results.length === 0) {
            var newErr = new Error();
            newErr.leval = 9;
            newErr.title = '查询入库记录失败';
            newErr.message = '未查询到入库记录！';
            deferred.reject(newErr);
            return;
        }
        deferred.resolve(results);
    });
    return deferred.promise;
}

function findDeliveryRecord(containerId) {
    var deferred = Q.defer();
    DeliveryRecordController.queryByCondition({
        Container: containerId,
        Status: {
            $ne: 2
        }
    }, function(err, results) {
        if (err) {
            var newErr = new Error();
            newErr.leval = 9;
            newErr.title = '查询配送记录失败';
            newErr.message = '查询物流配送失败！';
            deferred.reject(newErr);
        }
        if (results.length === 0) {
            var newErr = new Error();
            newErr.leval = 9;
            newErr.title = '查询配送记录失败';
            newErr.message = '未查询到配送记录！';
            deferred.reject(newErr);
            return;
        }
        deferred.resolve(results);
    });
    return deferred.promise;
}

function finishConfirm(array,wareHouseId) {
    var deferred = Q.defer();
        Transaction.BatchSaveByTran(array, function(err, result) {
            if (err) {
                var newErr = new Error();
                newErr.leval = 9;
                newErr.title = '交接确认';
                newErr.message = '交接确认失败！';
                deferred.reject(newErr);
                return;
            }
            SocketIo.emit(wareHouseId.toString(), 1);
            deferred.resolve(result);
        });
    return deferred.promise;
}
